<?php
// $Id: hotel_addons_upgrades_admin.inc,v 1.2.2.2 2010/07/19 09:34:25 larowlan Exp $

/**
 * @file
 * Addon/Upgraed Product admin settings & config functions.
 * @todo this file needs some love
 */

function hotel_addons_upgrades_settings_form() {
  $form = array();

  $foo = variable_get('hotel_booking_upgrade_product_classes', '');

  $product_class_filter = explode('|' , $foo);

  $results = db_query('SELECT pcid, name FROM {uc_product_classes} ORDER BY name');

  while ($result = db_fetch_array($results)) {
    $product_classes[$result['pcid']] = $result['name'];
  }

  $form['display'] = array(
    '#type'        => 'fieldset',
    '#title'       => t('Upgrade/Addon Product Classes'),
  );
  $form['display']['hotel_addons_upgrades_product_classes'] = array(
    '#type'          => 'checkboxes',
    '#title'         => '',
    '#description'   => t('Upgrade/Addon products will be limited to products in checked classes, or all products if nothing is checked.'),
    '#default_value' => $product_class_filter,
    '#options'       => $product_classes,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );

  return $form;

}


function hotel_addons_upgrades_settings_form_submit($form, &$form_state) {
  foreach ($form_state['values']['hotel_addons_upgrades_product_classes'] as $key => $value) {
    if (!$value == 0) {
      $selections[] = $value;
    }
  }
  variable_set('hotel_booking_upgrade_product_classes', isset($selections) ? implode('|', $selections) : '');
  drupal_set_message(t('Settings have been saved.'));
}

function hotel_addons_upgrades_show_items() {

  $addon_products = hotel_addons_upgrades_products_table();
  $addon_products .= l('Configure New Upgrade/Addon Product', 'admin/store/hotel_booking/upgrades_addons/add'). ' | ';
  $addon_products .= l('Limit Available Upgrade/Addon Product Classes', 'admin/store/hotel_booking/upgrades_addons/settings');

  $element = array(
    '#title' => t('Upgrade/Addon Products'),
    '#children' => $addon_products,
  );

  return theme('fieldset', $element);
}

function hotel_addons_upgrades_products_table() {
  $header = array(
    t('Product'),
    t('Details'),
    t('Available Days'),
    array('data' => t('Actions'), 'colspan' => 2),
  );

  $rows = array();
  $addon_products = hotel_addons_upgrades_get_product_list();
  if (is_array($addon_products)) {
    foreach ($addon_products as $addon_product) {
      $rows[] = array(
        l($addon_product['name'], 'admin/store/hotel_booking/upgrades_addons/'. $addon_product['apid']),
        check_plain($addon_product['detail']),
        check_plain($addon_product['days']),
        l(t('Edit'), 'admin/store/hotel_booking/upgrades_addons/'. $addon_product['apid']),
        l(t('Delete'), 'admin/store/hotel_booking/upgrades_addons/'. $addon_product['apid'] .'/delete'),
      );
    }
  }
  $table = theme('table', $header, $rows);

  return $table;
}

function hotel_addons_upgrades_get_product_list() {
  $results = db_query("SELECT bu.apid, bu.number, bu.daystay, bu.checkin, bu.checkout, bu.daysofweek, bu.monthsofyear, n.title FROM {hotel_booking_upgrades} AS bu, {node} AS n, {uc_products} AS p WHERE bu.model = p.model AND p.nid = n.nid");
  while ($result = db_fetch_array($results)) {
    $row = array();
    $row['apid'] = $result['apid'];
    $row['name'] = $result['title'];
    $detail = ($result['number'] == 0) ? 'Limit one' : 'Limit one per guest';
    if ($result['daystay'] == 0) {
      $detail .= ' per stay.';
    }
    else {
      $detail .= ' per day';
      if ($result['checkin'] == 0 && $result['checkout'] == 0) {
        $detail .= '.';
      }
      elseif ($result['checkin'] == 1 && $result['checkout'] == 1) {
        $detail .= ', Check-In & Check-Out dates included.';
      }
      elseif ($result['checkin'] == 1 && $result['checkout'] == 0) {
        $detail .= ', Check-In date included.';
      }
      else {
        $detail .= ', Check-Out date included.';
      }
    }
    $row['detail'] = $detail;
    $dow = unserialize($result['daysofweek']);
    $daysavailable = NULL;
    foreach ($dow as $day => $value) {
      if (!$daysavailable) {
        if ($value != '0') {
          $daysavailable = t($day);
        }
      }
      elseif ($value != '0') {
        $daysavailable .= ', '. t($day);
      }
    }
    $row['days'] = $daysavailable;
    $product_list[] = $row;
  }
  return $product_list;
}


function hotel_addons_upgrades_load($apid) {

  return db_fetch_array(db_query('SELECT bu.apid, bu.model, bu.number, bu.daystay, bu.checkin, bu.checkout, bu.daysofweek, bu.monthsofyear, bu.availableroomtypes, n.title FROM {hotel_booking_upgrades} AS bu, {node} AS n, {uc_products} AS p WHERE bu.model = p.model AND p.nid = n.nid AND bu.apid = %d', $apid));

}


function hotel_addons_upgrades_items_form($form_state, $addon_id = 0) {

  $ap = hotel_addons_upgrades_load($addon_id);

  if ($ap['apid'] == 0) {
    drupal_set_title(t('New Upgrade/Addon Product'));
  }
  else {
    drupal_set_title('Configure Upgrade/Addon Product: '. $ap['title']);
  }

  if (!$ap['model']) {
    $ap['model'] == '0';
  }


  // Build a query that selects all products, or those of applicable types, but not those
  // that have already been configured as an upgrade/addon item.

  $query = 'SELECT p.model, n.title FROM {node} AS n, {uc_products} AS p WHERE n.nid = p.nid AND NOT EXISTS (SELECT u.model FROM {hotel_booking_upgrades} AS u WHERE p.model = u.model)';
  $foo = variable_get('hotel_booking_upgrade_product_classes', '');
  if ($foo) {
    $upc = explode('|', $foo);
    for ($i = 0; $i < sizeof($upc); $i++) {
      if ($i == 0) {
        $query .= ' AND n.type = "'. $upc[$i] .'" AND NOT EXISTS (SELECT u.model FROM {hotel_booking_upgrades} AS u WHERE p.model = u.model)';
      }
      else {
        $query .= ' OR (n.nid = p.nid AND n.type = "'. $upc[$i] .'" AND NOT EXISTS (SELECT u.model FROM {hotel_booking_upgrades} AS u WHERE p.model = u.model))';
      }
    }
  }
  $query .= ' ORDER BY title';

  // If this is a new upgrade/addon item, create a blank select option prompting a selection be made.
  if ($ap['apid'] == 0) {
    $option_list = array('0' => '-- Please make a selection --'); }

  // If this is an existing upgrade/addon item, manually add the option to
  // the top of the select list, as the query above won't have returned it.
  if ($ap['apid'] > 0) {
    $option_list[$ap['model']] = $ap['title']; }

  $results = db_query($query);
  while ($result = db_fetch_array($results)) {
    $option_list[$result['model']] = $result['title'];
  }

  // Build list of room types
  $allroomtypes = array();
  $results = db_query('SELECT hrt.nid, n.title FROM {hotel_booking_room_types} AS hrt, {node} AS n WHERE n.nid = hrt.nid');
  while ($result = db_fetch_array($results)) {
    $allroomtypes[$result['nid']] = check_plain($result['title']);
  }

  // Gather default value(s) for room type limits.
  if ($ap['availableroomtypes']) {
    $availableroomtypes = unserialize($ap['availableroomtypes']);
  }
  else {
    $availableroomtypes = array();
  }

  $form['apid'] = array(
    '#type'          => 'value',
    '#value'         => $ap['apid'],
  );
  $form['product_name'] = array(
    '#type'          => 'select',
    '#title'         => t('Upgrade/Addon Product'),
    '#default_value' => $ap['model'],
    '#options'       => $option_list,
    '#required'      => TRUE,
    '#description'   => t('Select an existing product from the list, or '. l(t('create a new product'), 'node/add') .'.'),
  );
  $form['limits'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('Limits'),
    '#description'   => t('The number of this item that can be added to a room booking will be limited by the values set for quantity and frequency.'),
  );
  $form['limits']['number'] = array(
    '#type'          => 'radios',
    '#title'         => t('Quantity'),
    '#default_value' => ($ap['number']) ? $ap['number'] : 0,
    '#options'       => array(t('One'), t('One per Guest')),
  );
  $form['limits']['daystay'] = array(
    '#type'          => 'radios',
    '#title'         => t('Frequency'),
    '#default_value' => ($ap['daystay']) ? $ap['daystay'] : 0,
    '#options'       => array(t('For the entire stay'), t('For each day of the stay')),
  );
  $form['limits']['roomtypes'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('Limit by Room Type'),
    '#description'   => t('Default: Available to all room types. <em>(all room types unchecked)</em>'),
    '#collapsible'   => TRUE,
    '#collapsed'     => TRUE,
  );
  $form['limits']['roomtypes']['availableroomtypes'] = array(
    '#type'          => 'checkboxes',
    '#description'   => t('Select <em>specific room types</em> to limit availability of this upgrade/addon to <strong>just those room types</strong>, or <em>uncheck all</em> to make available to <strong>all room types.</strong>'),
    '#default_value' => $availableroomtypes,
    '#options'       => $allroomtypes,
  );
  $form['limits']['checkinout'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('Check-In/Out Options'),
    '#description'   => t('If this product applies to each day of the stay, should it be available on Check-In and Check-Out dates?'),
    '#collapsible'   => TRUE,
    '#collapsed'     => TRUE,
  );
  $form['limits']['checkinout']['checkin'] = array(
    '#type'          => 'radios',
    '#title'         => t('Available on Check-In date'),
    '#default_value' => ($ap['checkin']) ? $ap['checkin'] : 0,
    '#options'       => array(1 => t('Yes'), 0 => t('No')),
  );
  $form['limits']['checkinout']['checkout'] = array(
    '#type'          => 'radios',
    '#title'         => t('Available on Check-Out date'),
    '#default_value' => ($ap['checkout']) ? $ap['checkout'] : 0,
    '#options'       => array(1 => t('Yes'), 0 => t('No')),
  );
  $form['limits']['days'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('Available Days of Week'),
    '#description'   => t('What days of the week is this upgrade/addon available?'),
    '#collapsible'   => TRUE,
    '#collapsed'     => TRUE,
  );
  $form['limits']['days']['daysofweek'] = array(
    '#type'          => 'checkboxes',
    '#description'   => t('This upgrade/addon option will only be displayed on the list if the booking contains days available.'),
    '#options'       => array(
      'Sun' => t('Sunday'),
      'Mon' => t('Monday'),
      'Tue' => t('Tuesday'),
      'Wed' => t('Wednesday'),
      'Thr' => t('Thursday'),
      'Fri' => t('Friday'),
      'Sat' => t('Saturday'),
    ),
    '#default_value'       => ($ap['daysofweek']) ? unserialize($ap['daysofweek']) : array('Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'),
  );
  $form['limits']['months'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('Available Months of Year'),
    '#description'   => t('What months of the year is this upgrade/addon available?'),
    '#collapsible'   => TRUE,
    '#collapsed'     => TRUE,
  );
  $form['limits']['months']['monthsofyear'] = array(
    '#type'          => 'checkboxes',
    '#description'   => t('This upgrade/addon option will only be displayed on the list if the booking falls within available months.'),
    '#options'       => array(
      '1' => t('January'),
      '2' => t('February'),
      '3' => t('March'),
      '4' => t('April'),
      '5' => t('May'),
      '6' => t('June'),
      '7' => t('July'),
      '8' => t('August'),
      '9' => t('September'),
      '10' => t('October'),
      '11' => t('November'),
      '12' => t('December'),
    ),
    '#default_value'       => ($ap['monthsofyear']) ? unserialize($ap['monthsofyear']) : array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
  );
  if ($ap['apid'] == 0) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
    );
  }
  else {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Update'),
    );
    $form['delete_button'] = array(
      '#type' => 'submit',
      '#name' => 'delete',
      '#value' => t('Delete'),
    );
  }
  return $form;
}


function hotel_addons_upgrades_items_form_validate($form, &$form_state) {
  if ($form_state['values']['product_name'] == '0') {
    form_set_error('product_name', t('You must select a product.'), FALSE);
    return;
  }
  if (isset($form_state['values']['delete'])) {
    drupal_goto('admin/store/hotel_booking/upgrades_addons/'. $form_state['values']['apid'] .'/delete');
  }
}


function hotel_addons_upgrades_items_form_submit($form, &$form_state) {
  $roomlimits = FALSE;
  foreach ($form_state['values']['availableroomtypes'] as $rtid => $onoff) {
    if ($onoff) {
      $roomlimits = TRUE;
    }
  }
  $availableroomtypes = ($roomlimits) ? serialize($form_state['values']['availableroomtypes']) : NULL;

  if ($form_state['values']['apid'] < 1) {
    $sql = "INSERT INTO {hotel_booking_upgrades} (model, number, daystay, checkin, checkout, daysofweek, monthsofyear, availableroomtypes) VALUES ('%s', %d, %d, %d, %d, '%s', '%s', '%s')";
    db_query($sql, $form_state['values']['product_name'], $form_state['values']['number'], $form_state['values']['daystay'], $form_state['values']['checkin'], $form_state['values']['checkout'], serialize($form_state['values']['daysofweek']), serialize($form_state['values']['monthsofyear']), $availableroomtypes);
  }
  else {
    $id = $form_state['values']['apid'];
    $sql = "UPDATE {hotel_booking_upgrades} SET model='%s', number=%d, daystay=%d, checkin=%d, checkout=%d, daysofweek='%s', monthsofyear='%s', availableroomtypes='%s' WHERE apid=%d";
    db_query($sql, $form_state['values']['product_name'], $form_state['values']['number'], $form_state['values']['daystay'], $form_state['values']['checkin'], $form_state['values']['checkout'], serialize($form_state['values']['daysofweek']), serialize($form_state['values']['monthsofyear']), $availableroomtypes, $id);
  }
  $result = db_fetch_array(db_query('SELECT n.title FROM {node} AS n, {uc_products} AS p WHERE p.nid = n.nid AND p.model = "%s"', $form_state['values']['product_name']));
  drupal_set_message(t($result['title'] .' settings saved.'));
  $form_state['redirect'] = "admin/store/hotel_booking/upgrades_addons";
}


function hotel_addons_upgrades_items_delete_form($form_state, $apid = 0) {
  $ap = hotel_addons_upgrades_load($apid);

  if ($ap['apid'] == 0) {
    drupal_goto('admin/store/hotel_booking/upgrades_addons');
  }
  if (!$ap['apid']) {
    drupal_goto('admin/store/hotel_booking/upgrades_addons');
  }

  drupal_set_title(t('Delete !name', array('!name' => $ap['title'])));

  $form['apid'] = array(
    '#type' => 'value',
    '#value' => $ap['apid'],
  );
  $output = confirm_form($form,
    t('Remove !name from Upgrade/Addon item list?', array('!name' => $ap['title'])),
    'admin/store/hotel_booking/upgrades_addons',
    '',
    t('Delete'),
    t('Cancel')
  );

  return $output;
}

function hotel_addons_upgrades_items_delete_form_submit($form, $form_state) {
  if ($form_state['values']['confirm']) {
    db_query('DELETE FROM {hotel_booking_upgrades} WHERE apid=%d', $form_state['values']['apid']);

    drupal_set_message(t('Upgrade/Addon product removed.'));
  }

  return 'admin/store/hotel_booking/upgrades_addons';
}
